/**
 * 
 */
package cn.jhz.learn.community_dynamic.security.config;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;

import cn.jhz.learn.community_dynamic.security.filter.JsonPhoneSmsCodeAuthenticationFilter;
import cn.jhz.learn.community_dynamic.security.filter.JsonUsernamePasswordAuthenticationFilter;


/**
 * @author machine005
 *
 */
public class JsonLoginDsl extends AbstractHttpConfigurer<JsonLoginDsl, HttpSecurity> {
    private final AbstractAuthenticationProcessingFilter usernamePasswordAuthenticationProcessingFilter;
    private final AbstractAuthenticationProcessingFilter phoneSmsCodeAuthenticationProcessingFilter;
    
    public JsonLoginDsl(AbstractAuthenticationProcessingFilter usernamePasswordAuthenticationProcessingFilter, 
	    AbstractAuthenticationProcessingFilter phoneSmsCodeAuthenticationProcessingFilter) {
        this.usernamePasswordAuthenticationProcessingFilter = usernamePasswordAuthenticationProcessingFilter;
        this.phoneSmsCodeAuthenticationProcessingFilter = phoneSmsCodeAuthenticationProcessingFilter;
    }
    
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //不将认证后的context放入session
	NullAuthenticatedSessionStrategy nullAuthenticatedSessionStrategy = new NullAuthenticatedSessionStrategy();
	usernamePasswordAuthenticationProcessingFilter.setSessionAuthenticationStrategy(nullAuthenticatedSessionStrategy);
	phoneSmsCodeAuthenticationProcessingFilter.setSessionAuthenticationStrategy(nullAuthenticatedSessionStrategy);
        //设置Filter使用的AuthenticationManager,这里取公共的即可
	usernamePasswordAuthenticationProcessingFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
	phoneSmsCodeAuthenticationProcessingFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        //指定Filter的位置
        //将filter放到logoutFilter之前
        http.addFilterAfter(postProcess(usernamePasswordAuthenticationProcessingFilter), LogoutFilter.class);
        http.addFilterAfter(postProcess(phoneSmsCodeAuthenticationProcessingFilter), LogoutFilter.class);
    }
    
    public static JsonLoginDsl jsonLoginDsl(JsonUsernamePasswordAuthenticationFilter usernamePasswordAuthenticationProcessingFilter, 
	    JsonPhoneSmsCodeAuthenticationFilter phoneSmsCodeAuthenticationProcessingFilter) {
        return new JsonLoginDsl(usernamePasswordAuthenticationProcessingFilter, phoneSmsCodeAuthenticationProcessingFilter);
    }
}
